<script setup>

import { onMounted, onUnmounted, ref } from "vue";
import PKRoomIframe from "@/components/PKRoomIframe.vue";
import * as tetrApi from "@/api/tetr.js";

import { Promotion } from '@element-plus/icons-vue';

// 页面对象的引用
const refPkWindow = ref(null)
const refPkContentLeft = ref(null)
const refPkContentRight = ref(null)

// 左侧与右侧房间的信息
const leftRoom = ref({ room: 0, anchor: { face: '', uname: '' }, video: { room_id: '' }, isLoaded: false, winNum: 0 });
const rightRoom = ref({ room: 0, anchor: { face: '', uname: '' }, video: { room_id: '' }, isLoaded: false, winNum: 0 });

// 房间号输入框内容
const inputRoomLeft = ref('')
const inputRoomRight = ref('')

// 计时器
const time = ref(0)
const pkTimer = ref(null)

// 启动计时器
const startTimer = () => {
    time.value == 0;
    pkTimer.value = setInterval(() => {
        time.value += 1
    }, 1000)
}

// 停止计时器
const stopTimer = () => {
    if ( pkTimer.value ) {
        clearInterval(pkTimer.value)
    }
}

// 重置计时器
const resetTimer = () => {
    stopTimer();
    time.value = 0
}

// 时间格式化
const formatTime = (time) => {
    const minutes = Math.floor((time % 3600) / 60)
    const seconds = time % 60
    return `${ minutes < 10 ? '0' + minutes : minutes }:${ seconds < 10 ? '0' + seconds : seconds }`
}

// 加载左侧房间信息
const loadLeftRoom = (roomId) => {
    leftRoom.value.isLoaded = false
    // 重置缩放和位置
    iframe1Scale.value = 0
    refPkContentLeft.value.style.top = 0
    refPkContentLeft.value.style.left = 0
    refPkContentLeft.value.style.transform = ``
    tetrApi.roomInfo({ roomId: roomId }).then(res => {
        leftRoom.value = res.data;
        leftRoom.value.isLoaded = true
    });
}

// 加载右侧房间信息
const loadRightRoom = (roomId) => {
    rightRoom.value.isLoaded = false
    // 重置缩放和位置
    iframe2Scale.value = 0
    refPkContentRight.value.style.top = 0
    refPkContentRight.value.style.left = 0
    refPkContentRight.value.style.transform = ``
    tetrApi.roomInfo({ roomId: roomId }).then(res => {
        rightRoom.value = res.data;
        rightRoom.value.isLoaded = true
    });
}

// 缩放比例
const iframe1Scale = ref(0);
const iframe2Scale = ref(0);

/**
 * 调整PkWindow的大小为16比9
 */
const resizePkWindow = () => {
    // 调整主PK窗口大小
    refPkWindow.value.style.height = `${ refPkWindow.value.offsetWidth * 9 / 16 }px`

    // 内部窗口宽度适配
    refPkContentLeft.value.style.width = `${ refPkWindow.value.offsetWidth }px`
    refPkContentRight.value.style.width = `${ refPkWindow.value.offsetWidth }px`

    // 内部窗口高度适配
    refPkContentLeft.value.style.height = `${ refPkWindow.value.offsetHeight }px`
    refPkContentRight.value.style.height = `${ refPkWindow.value.offsetHeight }px`
}

/**
 * 滚轮放大缩小左侧窗口
 * @param e
 */
const handleMouseWheelLeft = (e) => {
    const delta = e.deltaY > 0 ? -1 : 1
    iframe1Scale.value += delta * 0.05
    iframe1Scale.value = Math.max(0, Math.min(3, iframe1Scale.value))
    refPkContentLeft.value.style.transform = `scale(${ 1 + iframe1Scale.value })`
}

// 左侧窗口缩放管理变量
let isMouseDownLeft = false

// 拖拽时移动左侧窗口
const handleMouseDownLeft = (e) => {
    isMouseDownLeft = true
}
const handleMouseMoveLeft = (e) => {
    if ( isMouseDownLeft ) {

        refPkContentLeft.value.style.cursor = 'grabbing'

        // 获取当前位置
        const top = refPkContentLeft.value.style.top || 0
        const left = refPkContentLeft.value.style.left || 0

        // 计算目标新位置
        let newTopValue = parseInt(top) + e.movementY
        let newLeftValue = parseInt(left) + e.movementX

        // 限制拖动范围
        newTopValue = Math.min(0, newTopValue)
        newTopValue = Math.max(newTopValue, -1 * iframe1Scale.value * refPkContentLeft.value.offsetHeight)
        newLeftValue = Math.min(0, newLeftValue)
        newLeftValue = Math.max(newLeftValue, -1 * ((iframe1Scale.value + 1) * refPkContentLeft.value.offsetWidth - refPkContentLeft.value.offsetWidth / 2))

        // 重设位置
        refPkContentLeft.value.style.left = `${ newLeftValue }px`
        refPkContentLeft.value.style.top = `${ newTopValue }px`
    }
}
const handleMouseUpLeft = (e) => {
    isMouseDownLeft = false
    refPkContentLeft.value.style.cursor = 'default'
}

/**
 * 滚轮放大缩小右侧窗口
 * @param e
 */
const handleMouseWheelRight = (e) => {
    const delta = e.deltaY > 0 ? -1 : 1
    iframe2Scale.value += delta * 0.05
    iframe2Scale.value = Math.max(0, Math.min(3, iframe2Scale.value))
    refPkContentRight.value.style.transform = `scale(${ 1 + iframe2Scale.value })`
}

// 右侧窗口缩放管理变量
let isMouseDownRight = false

// 拖拽时移动右侧窗口
const handleMouseDownRight = (e) => {
    isMouseDownRight = true
}
const handleMouseMoveRight = (e) => {
    if ( isMouseDownRight ) {
        refPkContentRight.value.style.cursor = 'grabbing'

        // 获取当前位置
        const top = refPkContentRight.value.style.top || 0
        const left = refPkContentRight.value.style.left || 0

        // 计算目标新位置
        let newTopValue = parseInt(top) + e.movementY
        let newLeftValue = parseInt(left) + e.movementX

        // 限制拖动范围
        newTopValue = Math.min(0, newTopValue)
        newTopValue = Math.max(newTopValue, -1 * iframe2Scale.value * refPkContentRight.value.offsetHeight)
        newLeftValue = Math.min(0, newLeftValue)
        newLeftValue = Math.max(newLeftValue, -1 * ((iframe2Scale.value + 1) * refPkContentRight.value.offsetWidth - refPkContentRight.value.offsetWidth / 2))

        // 重设位置
        refPkContentRight.value.style.left = `${ newLeftValue }px`
        refPkContentRight.value.style.top = `${ newTopValue }px`
    }
}
const handleMouseUpRight = (e) => {
    isMouseDownRight = false
    refPkContentLeft.value.style.cursor = 'default'
}

// 绑定时间操作热键
const bindHotkey = (e) => {
    if ( e.key === 'd' ) {
        startTimer()
    }
    if ( e.key === 'c' ) {
        stopTimer()
    }
    if ( e.key === 'e' ) {
        resetTimer()
    }
}

// 挂载时调整窗口大小
onMounted(() => {
    resizePkWindow()
    window.addEventListener('keydown', bindHotkey)
    window.addEventListener('resize', resizePkWindow)
})

// 卸载时移除事件监听
onUnmounted(() => {
    window.removeEventListener('keydown', bindHotkey)
    window.removeEventListener('resize', resizePkWindow)
})

// 导出方法
defineExpose({
    loadLeftRoom, loadRightRoom
})

</script>

<template>
    <div class="pkToolBar">
        <div class="roomInfo">
            <div class="left">
                <div class="action">
                    <div class="input">
                        <el-input
                                v-model="inputRoomLeft"
                                style="width: 100%"
                                placeholder="请输入房间号"
                                class="input-with-select"
                                size="small"
                        >
                            <template #append>
                                <el-button v-btn :icon="Promotion" @click="loadLeftRoom(inputRoomLeft)"/>
                            </template>
                        </el-input>
                    </div>
                    <div class="win">
                        <el-rate v-model="leftRoom.winNum"
                                 clearable
                                 show-score
                                 text-color="#ff9900"
                                 score-template="{value} 胜场"/>
                    </div>
                </div>
                <div class="top">
                    <div class="avatar">
                        <el-avatar :size="48" :src="leftRoom.anchor.face"/>
                    </div>
                    <div class="info">
                        <div class="name">
                            <a target="_blank" :href="`https://live.bilibili.com/${leftRoom.video.room_id}`">{{ leftRoom.isLoaded ? leftRoom.anchor.uname : '未加载直播间' }}</a>
                        </div>
                        <div class="id">ID {{ leftRoom.isLoaded ? leftRoom.video.room_id : '<-------->' }}</div>
                        <div class="status">{{ leftRoom.video.live_status === 1 ? '已开播' : '未开播' }}</div>
                    </div>
                </div>
            </div>
            <div class="center">
                <div class="timer">
                    {{ formatTime(time) }}
                </div>
                <div class="action">
                    <el-button v-btn type="danger" link @click="resetTimer">重置计时(E)</el-button>
                    <el-button v-btn type="success" link @click="startTimer">开始计时(D)</el-button>
                    <el-button v-btn type="warning" link @click="stopTimer">停止计时(C)</el-button>
                </div>
            </div>
            <div class="right">
                <div class="action">
                    <div class="input">
                        <el-input
                                v-model="inputRoomRight"
                                style="width: 100%"
                                placeholder="请输入房间号"
                                class="input-with-select"
                                size="small"
                        >
                            <template #append>
                                <el-button v-btn :icon="Promotion" @click="loadRightRoom(inputRoomRight)"/>
                            </template>
                        </el-input>
                    </div>
                    <div class="win">
                        <el-rate v-model="rightRoom.winNum"
                                 clearable
                                 show-score
                                 text-color="#ff9900"
                                 score-template="{value} 胜场"/>
                    </div>
                </div>
                <div class="top">
                    <div class="avatar">
                        <el-avatar :size="48" :src="rightRoom.anchor.face"/>
                    </div>
                    <div class="info">
                        <div class="name">{{ rightRoom.isLoaded ? rightRoom.anchor.uname : '未加载直播间' }}</div>
                        <div class="id">ID {{ rightRoom.isLoaded ? rightRoom.video.room_id : '<-------->' }}</div>
                        <div class="status">{{ rightRoom.video.live_status === 1 ? '已开播' : '未开播' }}</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="pk-window" ref="refPkWindow">
        <div class="pk-screen">
            <div class="pk-content"
                 @wheel.prevent="handleMouseWheelLeft"
                 @mousedown.prevent="handleMouseDownLeft"
                 @mousemove.prevent="handleMouseMoveLeft"
                 @mouseup.prevent="handleMouseUpLeft"
                 ref="refPkContentLeft">
                <PKRoomIframe v-show="leftRoom.isLoaded" class="pk-iframe" :room="leftRoom.video.room_id"></PKRoomIframe>
            </div>
        </div>
        <div class="pk-screen">
            <div class="pk-content"
                 @wheel.prevent="handleMouseWheelRight"
                 @mousedown.prevent="handleMouseDownRight"
                 @mousemove.prevent="handleMouseMoveRight"
                 @mouseup.prevent="handleMouseUpRight"
                 ref="refPkContentRight">
                <PKRoomIframe v-show="rightRoom.isLoaded" class="pk-iframe" :room="rightRoom.video.room_id"></PKRoomIframe>
            </div>
        </div>
    </div>
</template>

<style>

</style>

<style scoped lang="scss">
.pkToolBar {
    width: 100%;
    user-select: none;

    img {
        -webkit-user-drag: none;
    }

    .roomInfo {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 13px;
        padding: 10px 0;

        .input {
            padding: 5px 0;
        }

        .info {

            .name, a {
                font-size: 16px;
                font-weight: 700;
                color: #333;
            }

            .id {
                font-size: 14px;
                color: #666;
            }
        }

        .win {
            display: flex;
            align-items: center;
            justify-content: flex-start;
        }

        .left, .right {
            display: flex;
            align-items: center;
            justify-content: center;

            .top {
                display: flex;
                align-items: center;
                justify-content: center;
                padding-left: 20px;
            }

            .avatar {
                padding-right: 12px;
            }
        }

        .center {
            display: flex;
            align-items: center;
            justify-content: center;
            flex-direction: column;

            .timer {
                font-size: 38px;
            }

            .action {

            }
        }
    }
}

.pk-window {
    width: 100%;
    background: #242424;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
    user-select: none;

    .pk-screen {
        width: 50%;
        height: 100%;
        overflow: hidden;
        background: #242424;
        user-select: none;

        .pk-content {
            user-select: none;
            position: relative;
            transform-origin: top left;

            .pk-iframe {
                top: 0;
                left: 0;
                position: absolute;
            }
        }
    }
}
</style>
